package cn.touna.jss.modules.third.sifa;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.properties.disconf.SifaProperties;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.sifa.entity.SiFaRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/**
 * 司法
 */
@Service
public class SiFaService {

    private static final Logger logger = LogManager.getLogger(SiFaService.class);

    private static HttpClientBuilder builder;

    @Autowired
    private SifaProperties config;


    @ApiMapping(value = "sifa.shesu", desc = "司法.涉诉信息")
    public Response sifaShesu(SiFaRequestEntity request) {
        Response response = ValidUtil.valid(request);
        if (response != null) {
            return response;
        }
        response = new Response();
        String url = config.getRequestUrl();
        JSONObject json = new JSONObject();
        json.put("uid", config.getUid());
        json.put("pwd", config.getPwd());
        json.put("expire", config.getExpire());
        String authJson = json.toJSONString();

        json.clear();
        json.put("name", request.getName());
        json.put("id", request.getIdCard());
        String queryJson = json.toJSONString();

        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient();
            HttpPost req = new HttpPost(url);
            req.setHeader("shesu-auth", authJson);

            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            params.add(new BasicNameValuePair("query", queryJson));
            req.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            HttpResponse result = httpClient.execute(req);

            StatusLine sl = result.getStatusLine();
            HttpEntity body = result.getEntity();
            if (sl == null || null == body) {
                logger.error("jss调用【司法涉诉信息】返回异常,sifaShesu,queryJson:{}", queryJson);
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR);
            }

            String s = EntityUtils.toString(body, "UTF-8");
            logger.info("[司法涉诉信息返回结果] queryJson:{},result:{}", queryJson, s);
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC,s);
        } catch (Exception e) {
            logger.error("jss调用【司法涉诉信息】异常,sifaShesu,queryJson:{}", queryJson, e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        } finally {
            if(null != httpClient){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private CloseableHttpClient getHttpClient() throws Exception {
        if (builder == null) {
            builder = HttpClientBuilder.create();

            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };

            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            };

            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new X509TrustManager[]{tm}, null);

            SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(ctx, hv);

            builder.setSSLSocketFactory(f);
        }

        return builder.build();

    }
}